from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import render

# Create your views here.
from django.shortcuts import render,redirect
from django.views import View
from django.db import DatabaseError
from django.urls import reverse
from django.contrib.auth import login, authenticate, logout
# Create your models here.
from django import http
import re
from users.models import User
from meiduo_project.utils.response_code import RETCODE
from django_redis import get_redis_connection
from meiduo_project.settings.VerificationSite import SMS_Verification


# 手机重复查询
class MobileCountView(View):

    def get(self, request, mobile):
        """
               :param request: 请求对象
               :param username: 用户名
               :return: JSON
        """
        # 使用mobile查询对应的记录条数，筛选，filter返回的是满足条件的结果集
        count = User.objects.filter(mobile=mobile).count()
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'count': count})


# 用户名重复查询
class UsernameCountView(View):

    def get(self, request, username):
        """
               :param request: 请求对象
               :param username: 用户名
               :return: JSON
        """
        # 使用nusername查询对应的记录条数，筛选，filter返回的是满足条件的结果集
        count = User.objects.filter(username=username).count()
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'count': count})


class Register(View):

    def get(self, request):
        """返回用户页面"""
        return render(request, "register.html")

    def post(self, request):
        """实现用户注册业务逻辑"""
        # 接收数据
        username = request.POST.get('username')
        password = request.POST.get('password')
        password2 = request.POST.get('password2')
        mobile = request.POST.get('mobile')
        sms_code_client = request.POST.get('sms_code')
        allow = request.POST.get('allow')
        # 检验数据
        # 判断参数是否齐全：all([])，回去检验所有值元素是否为空，只要有一个空则返回false
        if not all([username, password, password2, mobile, allow]):
            return http.HttpResponseForbidden('缺少必传参数111')
        if not re.match("^[a-zA-Z0-9_-]{5,20}$", username):
            return http.HttpResponseForbidden("请输入5-20个字符的用户名")
        if not re.match("^[a-zA-Z0-9]{8,20}$", password):
            return http.HttpResponseForbidden('请输入8-20位的密码')
        if password2 != password:
            return http.HttpResponseForbidden('两次输入的密码不一致')
        if not re.match('^1[3-9]\d{9}$', mobile):
            return http.HttpResponseForbidden('请输入正确的手机号码')

        """短信验证判断开关"""
        if SMS_Verification == 1:
            # 判断验证码是否正确
            redis_conn = get_redis_connection('verify_code')
            sms_code_server = redis_conn.get('sms_%s'%mobile)
            if sms_code_server is None:
                return render(request, 'register.html', {'sms_code_errmsg': '无效的短信验证码'})
            if sms_code_client != sms_code_server.decode():
                return render(request, 'register.html', {'sms_code_errmsg': '输入短信验证码有误'})

        if allow == "no":
            return http.HttpResponseForbidden('请勾选同意用户协议')

        # 保存数据
        try:
            user = User.objects.create_user(username=username, password=password, mobile=mobile)

        except DatabaseError:
            return render(request, "register.html", {'register_errmsg': "注册失败"})

        # 登入用户，实现状态保持
        login(request, user)

        # 实现登录后用户名展示，将用户名存在cookie
        response = redirect(reverse('contents:index'))
        # 实现登录后用户名展示，将用户名存在cookie
        response.set_cookie('username', user.username, max_age=3600*24*15)

        # 重定向首页
        return response


class LoginView(View):

    def get(self, request):
        """
         提供登录界面
         :param request: 请求对象
         :return: 登录界面
         """
        return render(request, 'login.html')

    def post(self, request):
        """
        :param request:请求对象
        :return:登录结果
        """
        # 接收参数
        # 接受参数
        next = request.GET.get('next')
        username = request.POST.get('username')
        password = request.POST.get('password')
        remembered = request.POST.get('remembered')

        # 校验参数
        # 1.判断参数是否齐全
        if not all([username, password]):
            return http.HttpResponseForbidden('缺少必传参数')

        # 2.判断用户名是否是5-20个字符
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return http.HttpResponseForbidden('请输入正确的用户名或手机号')

        # 3.判断密码是否是8-20个数字
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return http.HttpResponseForbidden('密码最少8位，最长20位')

        # 4.认证登录用户
        user = authenticate(username=username, password=password)
        if user is None:
            return render(request, 'login.html', {'account_errmsg': '用户名或密码错误'})

        # 实现状态保持
        login(request, user)

        # 设置状态保持的周期
        if remembered != 'on':
            # 没有记住用户：浏览器会话结束就过期
            request.session.set_expiry(0)
        else:
            # 记住用户：None表示两周后过期
            request.session.set_expiry(None)

        # 判断是需要重定向的页面
        if next:
            response = redirect(next)
        else:
            response = redirect(reverse('contents:index'))
        # 实现登录后用户名展示，将用户名存在cookie
        response.set_cookie('username', user.username, max_age=3600*24*15)

        # 响应登录结果，重定向首页
        return response


class LogoutView(View):
    """退出登录"""

    def get(self, request):
        """实现退出登录逻辑"""
        # 清理session
        logout(request)
        # 退出登录，重定向到登录页
        response = redirect(reverse('contents:index'))
        # 退出登录时清除cookie中的username
        response.delete_cookie('username')

        return response


class UserInfoView(LoginRequiredMixin, View):
    """用户中心"""

    def get(self, request):
        """提供个人信息界面"""
        return render(request, 'user_center_info.html')
